package com.ruoyi.project.bajiaostar.tGoodDetail.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.bajiaostar.tGood.domain.TGood;
import com.ruoyi.project.bajiaostar.tGood.service.ITGoodService;
import com.ruoyi.project.bajiaostar.tGoodOrder.domain.AdminMailGoodVo;
import com.ruoyi.project.bajiaostar.tGoodOrder.domain.TGoodOrder;
import com.ruoyi.project.bajiaostar.tGoodOrder.service.ITGoodOrderService;
import com.ruoyi.project.bajiaostar.user.dto.FindUserDetailDto;
import com.ruoyi.project.bajiaostar.user.dto.GetGoodDetailByGoodIdDto;
import com.ruoyi.project.bajiaostar.user.vo.SendGoodDetailVo;
import com.ruoyi.project.mail.service.IMailService;
import com.ruoyi.project.user.domain.TUser;
import com.ruoyi.project.user.service.ITUserService;
import com.ruoyi.project.utils.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.stereotype.Service;
import com.ruoyi.project.bajiaostar.tGoodDetail.mapper.TGoodDetailMapper;
import com.ruoyi.project.bajiaostar.tGoodDetail.domain.TGoodDetail;
import com.ruoyi.project.bajiaostar.tGoodDetail.service.ITGoodDetailService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.util.ObjectUtils;


/**
 * 商品详情信息Service业务层处理
 * 
 * @author wangwu
 * @date 2024-05-21
 */
@Service
@Slf4j
public class TGoodDetailServiceImpl implements ITGoodDetailService 
{
    @Autowired
    private TGoodDetailMapper tGoodDetailMapper;
    @Autowired
    ITUserService userService;
    @Autowired
    IMailService mailService;

    @Value("${ruoyi.profile}")
    private String filePath;
    @Autowired
    ITGoodService goodService;
    @Autowired
    ITGoodOrderService goodOrderService;

    /**
     * 查询商品详情信息
     * 
     * @param id 商品详情信息ID
     * @return 商品详情信息
     */
    @Override
    public TGoodDetail selectTGoodDetailById(Long id)
    {
        return tGoodDetailMapper.selectTGoodDetailById(id);
    }

    /**
     * 查询商品详情信息列表
     * 
     * @param tGoodDetail 商品详情信息
     * @return 商品详情信息
     */
    @Override
    public List<TGoodDetail> selectTGoodDetailList(TGoodDetail tGoodDetail)
    {
        return tGoodDetailMapper.selectTGoodDetailList(tGoodDetail);
    }

    @Override
    public List<String> getGoodDetailDateByGoodId(Long goodId) {
        return tGoodDetailMapper.getGoodDetailDateByGoodId(goodId);
    }

    /**
     * 新增商品详情信息
     * 
     * @param tGoodDetail 商品详情信息
     * @return 结果
     */
    @Override
    public int insertTGoodDetail(TGoodDetail tGoodDetail)
    {
        tGoodDetail.setCreateTime(DateUtils.getNowDate());
        return tGoodDetailMapper.insertTGoodDetail(tGoodDetail);
    }

    /**
     * 修改商品详情信息
     * 
     * @param tGoodDetail 商品详情信息
     * @return 结果
     */
    @Override
    public int updateTGoodDetail(TGoodDetail tGoodDetail)
    {
        tGoodDetail.setUpdateTime(DateUtils.getNowDate());
        return tGoodDetailMapper.updateTGoodDetail(tGoodDetail);
    }

    /**
     * 删除商品详情信息对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteTGoodDetailByIds(String ids)
    {
        return tGoodDetailMapper.deleteTGoodDetailByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除商品详情信息信息
     * 
     * @param id 商品详情信息ID
     * @return 结果
     */
    @Override
    public int deleteTGoodDetailById(Long id)
    {
        return tGoodDetailMapper.deleteTGoodDetailById(id);
    }

    @Override
    public List<TGoodDetail> getGoodDetailByGoodId(GetGoodDetailByGoodIdDto dto) {
        List<TGoodDetail> detailList = tGoodDetailMapper.getGoodDetailByGoodId(dto);
        if(!ObjectUtils.isEmpty(detailList)){
            for (TGoodDetail detail:detailList){
                detail.setSellOutFlag(0);

                TGoodOrder goodOrder=new TGoodOrder();
                goodOrder.setGoodDetailId(detail.getId());
                goodOrder.setOrderStatus(0);
                List<TGoodOrder> orderList = goodOrderService.selectTGoodOrderList(goodOrder);
                if(detail.getInventory() == 0 && ObjectUtils.isEmpty(orderList)){
                    detail.setSellOutFlag(1);
                }
            }
        }
        return detailList;
    }
    /**
     * 根据商品id发送商品详情
     * @param goodId
     * @param userId
     * @return
     */
    @Override
    public AjaxResult sendGoodDetail(Long goodId, Long userId) {
        TUser user = userService.selectTUserById(userId);
        if(ObjectUtils.isEmpty(user)){
            return AjaxResult.error("用户未登录或登录已失效");
        }
        List<TGoodDetail> details = tGoodDetailMapper.findGoodDetailByGoodId(goodId);
        if(ObjectUtils.isEmpty(details)){
            return AjaxResult.error("暂无可发送场次数据");
        }
        //获取商品
        TGood good = goodService.selectTGoodById(goodId);
        if(ObjectUtils.isEmpty(good)){
            return AjaxResult.error("商品不存在");
        }
        List<SendGoodDetailVo> exList=new ArrayList<>();
        details.forEach(detail->{
            SendGoodDetailVo vo=new SendGoodDetailVo();
            BeanUtils.copyProperties(detail,vo);
            vo.setGoodDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,detail.getGoodDate()));
            if(user.getUserIdentity().equals(1)){
                vo.setDefaultSettlementPrice(detail.getMemberSettlementPrice());

            }else if(user.getUserIdentity().equals(2)){
                vo.setDefaultSettlementPrice(detail.getTwoMemberSettlementPrice());
            }
            vo.setGoodName(good.getGoodName());
            vo.setUserMail(user.getMobile());
            exList.add(vo);
        });

        try {
            // 生成excel文件
            ByteArrayOutputStream out = ExcelUtil.generateExcel(exList, SendGoodDetailVo.class);
            String path=filePath+DateUtils.parseDateToStr(DateUtils.YYYYMMDDHHMMSS,new Date())+exList.get(0).getGoodName()+"商品详情.xlsx";
            FileOutputStream fos = new FileOutputStream(new File(path));
            out.writeTo(fos);
           // mailService.sendAttachmentMailMessage(exList.get(0).getUserMail(),exList.get(0).getGoodName()+"商品详情","商品详情在附件中，请查看",new ByteArrayResource(out.toByteArray()),exList.get(0).getGoodName()+"商品信息");
            mailService.sendAttachmentMailMessage(exList.get(0).getUserMail(),exList.get(0).getGoodName()+"商品详情","商品详情在附件中，请查看",path);

        } catch (Exception e) {
            log.error("发送管理员邮件失败：{}", e);
        }
        return AjaxResult.success();
    }

    /**
     * 修改旧树据状态
     *
     * @param id 商品详情信息ID
     * @return 结果
     */
    @Override
    public int updateGoodDetailStatusByGoodId(Long id) {
        return tGoodDetailMapper.updateGoodDetailStatusByGoodId(id);
    }

}
